import requests
import time
import os


def downloader(ind):
    digit = len(str(ind))
    string = "0"*(7-digit)+str(ind)      #### Application Number ####
    appnumber = "10"+ str(year) + string
    url = "http://plus.kipris.or.kr/openapi/rest/CitationService/citationInfoV3?applicationNumber=10"+ str(year) +string+"&accessKey=vHYkrSLI1J9sKpwQ/7gcIO7IGdVenwwsR7iKOigsXlQ="
    start = time.time()
    while True:
        try:
        	response = requests.get(url)
        	break
        except:
            time.sleep(0.1)
            pass
    end = time.time()
    A = end - start
    if A < 0.1:
        time.sleep(0.1 - A)
    data = response.content
    with open('D:\\KIPRIS\\Citation\\'+str(year) + '\\'+ str(appnumber)+'.xml', 'wb') as f:
        f.write(data)
    n = os.path.getsize('D:\\KIPRIS\\Citation\\'+str(year) + '\\'+ str(appnumber)+'.xml')
    size = round(n / 1024.0, 1)
    A = round(A, 3)
    print(str(appnumber)+ ' - ' + str(response.status_code)+ ' - ' +str(A) +'sec - ' +str(size) + 'KB')

lastlist = [169, 233, 126, 30, 91, 76, 132, 156, 287, 469, 555, 703, 611, 858, 782, 771, 908, 1018, 1060, 1177, 1463, 1701, 1846, 1906, 1995, 2398, 4455, 2914, 3261, 3139, 4015, 4722, 5070, 5303, 5924, 6394, 8633, 10587, 12759, 17062, 20051, 23315,25820, 28132, 31073, 36491, 45712, 78499, 90326, 92734]
# 1948~1997
consume = time.time()
for year in range(1990, 2017):
    last = lastlist[year-1948]
    indlist = range(1, last+1)
    for ind in indlist:
        downloader(ind)
print(time.time() - consume)